<script setup>
import { computed, reactive, ref } from 'vue';

import {
  ElButton,
  ElDialog,
  ElDivider,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
} from 'element-plus';

import { fileApi } from '#/api'; // 根据实际路径调整
import { $t } from '#/locales';
import { useCatalogStore } from '#/store';

// 定义组件的 `props`
const props = defineProps({
  modelValue: { type: Boolean, required: true },
  userId: { type: String, required: true },
  rootCatalog: { type: String, default: '' },
});

// 触发事件 `update:modelValue` 和 `refresh`
const emit = defineEmits(['update:modelValue', 'refresh']);

// 让 `dialogVisible` 可读写
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});

// 表单数据
const formData = reactive({
  data: { name: '' },
});

// 校验规则
const rules = {
  name: [{ required: true, message: '文件夹名不得为空！', trigger: 'blur' }],
};

const ruleFormRef = ref(null);
const catalogStore = useCatalogStore();

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
};

// 创建文件夹的逻辑
const handleCreate = async () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      // 检查文件夹名称是否合法
      const illegalChars = /[∧?*:"<>|]/;
      const folderName = formData.data.name;
      if (illegalChars.test(folderName)) {
        ElMessage.warning($t('page.resources.folderNameInvalidCharsMessage'));
        return;
      }

      // 获取父级目录 ID
      const parentCatalogId =
        catalogStore.currentCatalogId === '' &&
        catalogStore.rootCatalog === null
          ? props.rootCatalog
          : catalogStore.currentCatalogId || '';

      try {
        const response = await fileApi.createNewFolder({
          userId: props.userId,
          parentCatalogId,
          catalogName: folderName,
        });

        if (response) {
          emit('refresh'); // 通知父组件刷新目录
          ElMessage.success($t('page.resources.folderCreatedSuccessMessage'));
        } else {
          ElMessage.error('新建文件夹失败，请重试！');
        }
      } catch (error) {
        console.error(error);
      }

      // 关闭对话框
      closeDialog();
    }
  });
};

// 监听回车键
const handleEnterKey = () => {
  handleCreate();
};
</script>

<template>
  <ElDialog v-model="dialogVisible" width="350px" align-center destroy-on-close>
    <template #header>
      <div class="my-header">
        <h4 style="color: rgb(48 45 45)">
          {{ $t('page.resources.newFolder') }}
        </h4>
      </div>
    </template>

    <ElForm
      style="padding: 30px 30px 0 20px"
      :model="formData.data"
      label-width="120px"
      label-position="right"
      ref="ruleFormRef"
      :rules="rules"
    >
      <ElFormItem :label="$t('page.resources.folderNameLabel')" prop="name">
        <ElInput
          @keydown.enter="handleEnterKey"
          v-model.trim="formData.data.name"
          :placeholder="$t('page.resources.folderNamePlaceholder')"
          clearable
        />
      </ElFormItem>
      <ElFormItem>
        <ElDivider border-style="hidden" style="margin: 5px 0" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <span class="dialog-footer">
        <ElButton type="primary" @click="handleCreate">
          {{ $t('page.resources.create') }}
        </ElButton>
        <ElButton @click="closeDialog">
          {{ $t('page.resources.cancel') }}
        </ElButton>
      </span>
    </template>
  </ElDialog>
</template>
